package com.yc.bos.web.action;

import com.yc.bos.model.User;
import com.yc.bos.service.IUserService;
import com.yc.bos.utils.MD5Utils;
import com.yc.bos.web.action.base.BaseAction;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserAction extends BaseAction<User> {
    @Autowired
    private IUserService userService;

    Logger logger = Logger.getLogger(UserAction.class);

    public String login() {
        logger.info(getModel());

        String username = getModel().getUsername();
        String password = getModel().getPassword();
        HttpServletRequest request = ServletActionContext.getRequest();
        String serverCheckCode = (String) request.getSession().getAttribute("key");
        String clientCheckCode = request.getParameter("checkcode");
        if (serverCheckCode.equalsIgnoreCase(clientCheckCode) || clientCheckCode.equalsIgnoreCase("")) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Utils.text2md5(password));
            //另一种方法
            /*  User user = userService.login(username, password);
            if (user != null) {
                request.getSession().setAttribute("loginUser", user);
                return "home";
                } else {
                addActionError("登录失败，用户名密码不正确");
                    }
        } else {
            addActionError("登录失败，验证码不正确");
        }*/

            try {
                subject.login(token);
                User loginUser = (User) subject.getPrincipal();
                subject.getSession().setAttribute("loginUser", loginUser);
                return "home";
            } catch (AuthenticationException e) {
                e.printStackTrace();
                addActionError("登录失败，用户名密码不正确");
            }
        } else {
            addActionError("登录失败，验证码不正确");
        }
        return "loginfailure";
    }

    private String[] roleIds;

    public void setRoleIds(String[] roleIds) {
        this.roleIds = roleIds;
    }

    @Override
    public String save() {
        System.out.println(getModel());
        System.out.println(ArrayUtils.toString(roleIds));
        String pwd = MD5Utils.text2md5(getModel().getPassword());
        getModel().setPassword(pwd);
        if (roleIds != null && roleIds.length != 0) {
            userService.save(getModel(), roleIds);
        }else {
            logger.info("roleIds不能为空....");
        }
        return null;
    }

    @Override
    public String update() {
        return null;
    }

    @Override
    public String delete() {
        return null;
    }

    @Override
    public String list() {
        return null;
    }

    public String logout() {
        ServletActionContext.getRequest().getSession().invalidate();
        return "login";
    }

    public String editPassword() throws IOException {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        String newPwd = getModel().getPassword();
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        String userId = loginUser.getId();
        System.out.println("newPwd---" + newPwd + "userId---" + userId);
        userService.modifyPassword(newPwd, userId);
        response.setHeader("context-type", "text/json;charset=utf-8");
        response.getWriter().print("{\"success1\":\"1\"}");
        return NONE;

    }
    public void pageQuery() throws IOException {
        pd.setCurrentPage(page);
        pd.setPageSize(rows);
        System.out.println(page+"-----"+rows);
        userService.pageQuery(pd);

        responseJson(pd,new String[]{"currentPage","pageSize","detachedCriteria","roles"});


    }
}
